<?php

namespace app\index\controller\lawsuit;

use app\index\model\UM as UM;
use app\index\service\LawsuitService;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use ShidianUtil\Utils\CheckUtil;
use think\APP;
use think\exception\ValidateException;
use think\Request as Request;

/**
 * Lawsuit 控制器
 * Class Lawsuit
 * @package app\index\controller\lawsuit;
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037509
 * @see \app\index\validate\lawsuit\Lawsuit
 */
class Lawsuit
{
    // 请求参数
    private Request $request;

    // service
    private LawsuitService $service;

    public function __construct(Request $request, LawsuitService $lawsuitService)
    {
        $this->request = $request;
        $this->service = $lawsuitService;
    }

    /**
     * 新增|修改
     * @param UM $user
     * @return ApiResponse
     * @url /lawsuit/lawsuit/save
     */
    public function save(UM $user): ApiResponse
    {
        $request = $this->request;

        $params =  $request->param();

        $step = $params['step'] ?? 1;

        $sourceType = '';
        if ($this->request->header('pf', '') === 'h5') {
            $sourceType = 'h5';
        }
        $params['sourceType'] = $sourceType;

        if ($step == 1) {
            $data = $this->service->addStep1($user, $params);
        } elseif ($step == 2) {
            $data = $this->service->addStep2($user, $params);
        } else {
            throw new ValidateException('参数 step 不正确');
        }

        return ApiResponse::success($data);
    }

    public function read(UM $user): ApiResponse
    {

        $request = $this->request;

        $id = $request->param('id');

        if (!CheckUtil::isId($id)) {
            return ApiResponse::fail('缺少id参数');
        }

        return ApiResponse::success($this->service->read($user, $id));

    }
}
